package com.kh.pajx.sop.util.web;

import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * CSRF防护，随机验证因子
 * 可以使用Struts2自带的Token机制，但使用时需注意避免其本身的安全漏洞。
 * @author:	azzcsimp
 * @Createdate:	2014年12月18日 上午10:24:51
 */
public final class CSRFTokenManager {

	static final String CSRF_PARAM_NAME = "CSRFToken";

	public static final String CSRF_TOKEN_FOR_SESSION_ATTR_NAME = CSRFTokenManager.class.getName() + ".tokenval";

	private CSRFTokenManager() {
		
	};

	public static String getTokenForSession(HttpSession session) {
		String token = null;
		// I cannot allow more than one token on a session - in the case of two
		// requests trying to
		// init the token concurrently
		synchronized (session) {
			token = (String) session.getAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME);
			if (null == token) {
				token = UUID.randomUUID().toString();
				session.setAttribute(CSRF_TOKEN_FOR_SESSION_ATTR_NAME, token);
			}
		}
		return token;
	}

	public static String getTokenFromRequest(HttpServletRequest request) {
		return request.getParameter(CSRF_PARAM_NAME);
	}

}
